<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { OrganizationApi } from '@/api/OrganizationApi.ts'
import type { OrganizationVO, SearchRequest } from '@/api/Organization.ts'
import InfoDialog from './components/InfoDialog.vue'
import UpdateDialog from './components/UpdateDialog.vue'
import AddDialog from './components/AddDialog.vue'
import AddMemberDialog from './components/AddMemberDialog.vue'
import RemoveMemberDialog from './components/RemoveMemberDialog.vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined } from '@ant-design/icons-vue'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
  },
  {
    title: '组织名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    align: 'center',
  },
  {
    title: '成员数',
    dataIndex: 'currentMembers',
    key: 'currentMembers',
    align: 'center',
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
  },
]

const loading = ref(false)
const tableData = ref<OrganizationVO[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

const queryParams = ref<SearchRequest>({
  name: null,
  status: null,
})

const fetchData = async () => {
  loading.value = true
  try {
    const data = await OrganizationApi.search(queryParams.value)
    tableData.value = data?.records || []
    pagination.total = data?.records?.length || 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})

const onSearch = () => {
  pagination.current = 1
  fetchData()
}

const onReset = () => {
  queryParams.value = { name: null, status: null }
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag?.current || 1
  pagination.pageSize = pag?.pageSize || 10
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const router = useRouter()
const drawerOpen = ref(false)
const drawerMode = ref<'view' | 'edit' | 'add' | 'addMember' | 'removeMember'>('view')
const selectedOrg = ref<OrganizationVO | null>(null)

const openDrawer = (mode: 'view' | 'edit' | 'add' | 'addMember' | 'removeMember', org?: OrganizationVO) => {
  drawerMode.value = mode
  selectedOrg.value = org || null
  drawerOpen.value = true
}

const closeDrawer = () => {
  drawerOpen.value = false
  selectedOrg.value = null
}

const onUpdateSuccess = () => {
  fetchData()
  closeDrawer()
}

const onEdit = (record: OrganizationVO) => {
  openDrawer('edit', record)
}

const onView = (record: OrganizationVO) => {
  openDrawer('view', record)
}

const onAdd = () => {
  openDrawer('add')
}

const onAddMember = (record: OrganizationVO) => {
  openDrawer('addMember', record)
}

const onRemoveMember = (record: OrganizationVO) => {
  openDrawer('removeMember', record)
}

const onAction = (key: string, record?: any) => {
  switch (key) {
    case 'edit':
      onEdit(record)
      break
    case 'view':
      onView(record)
      break
    case 'addMember':
      onAddMember(record)
      break
    case 'removeMember':
      onRemoveMember(record)
      break
    default:
      break
  }
}

const onMenuClick = (info: any, record: any) => {
  onAction(String(info?.key ?? ''), record)
}

const getDrawerTitle = () => {
  switch (drawerMode.value) {
    case 'view':
      return '组织详情'
    case 'edit':
      return '修改组织信息'
    case 'add':
      return '新建组织'
    case 'addMember':
      return '添加成员'
    case 'removeMember':
      return '移除成员'
    default:
      return ''
  }
}
</script>

<template>
  <div class="w-full">
    <a-card
      title="组织管理"
      class="w-full rounded-lg shadow-sm"
      :bodyStyle="{ padding: '24px' }"
    >
      <template #extra>
        <a-button type="primary" @click="onAdd">新建组织</a-button>
      </template>

      <!-- 搜索表单 -->
      <div class="mb-6 flex flex-wrap items-center gap-4">
        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">组织名称:</label>
          <a-input
            v-model:value="queryParams.name"
            placeholder="输入组织名称"
            allow-clear
            @pressEnter="onSearch"
            class="w-[200px]"
          />
        </div>

        <div class="flex items-center gap-2">
          <label class="text-sm font-medium text-gray-700 whitespace-nowrap">状态:</label>
          <a-select
            v-model:value="queryParams.status"
            placeholder="选择状态"
            allow-clear
            class="w-[160px]"
          >
            <a-select-option :value="0">正常</a-select-option>
            <a-select-option :value="1">禁用</a-select-option>
          </a-select>
        </div>

        <div class="flex items-center gap-2">
          <a-button type="primary" @click="onSearch" class="px-6">
            搜索
          </a-button>
          <a-tooltip title="重置">
            <a-button
              @click="onReset"
              :shape="'default'"
              class="w-9 h-9 p-0 flex items-center justify-center"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-tooltip>
        </div>
      </div>

      <!-- 组织表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        rowKey="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showTotal: (total: number) => `共 ${total} 条`
        }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
        class="rounded-lg"
        :customRow="(record: any) => ({ class: 'hover:bg-slate-50' })"
        :customHeaderRow="() => ({ class: 'bg-slate-50 border-b-2 border-slate-200' })"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'description'">
            <span class="text-sm text-gray-700 line-clamp-2">{{ record.description || '暂无描述' }}</span>
          </template>
          <template v-else-if="column.key === 'createTime'">
            <span class="text-sm text-gray-700">{{ formatDate(record.createTime) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-dropdown :trigger="['click']">
              <a-button type="link" size="small" class="text-blue-600 hover:text-blue-800 font-medium">
                操作
              </a-button>
              <template #overlay>
                <a-menu @click="onMenuClick($event, record)" class="rounded-lg shadow-lg border border-gray-200">
                  <a-menu-item key="edit" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">修改</span>
                  </a-menu-item>
                  <a-menu-item key="view" class="hover:bg-blue-50 transition-colors">
                    <span class="text-gray-700">查看详情</span>
                  </a-menu-item>
                  <a-menu-divider class="my-1" />
                  <a-menu-item key="addMember" class="hover:bg-green-50 transition-colors">
                    <span class="text-green-600">添加成员</span>
                  </a-menu-item>
                  <a-menu-item key="removeMember" class="hover:bg-red-50 transition-colors">
                    <span class="text-red-600">移除成员</span>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>

  <a-drawer
    :open="drawerOpen"
    :width="620"
    placement="right"
    destroyOnClose
    @close="closeDrawer"
  >
    <template #title>
      {{ getDrawerTitle() }}
    </template>
    <InfoDialog
      v-if="drawerMode === 'view' && selectedOrg"
      :organization="selectedOrg"
      @close="closeDrawer"
    />
    <UpdateDialog
      v-else-if="drawerMode === 'edit' && selectedOrg"
      :organization="selectedOrg"
      @close="closeDrawer"
      @success="onUpdateSuccess"
    />
    <AddDialog
      v-else-if="drawerMode === 'add'"
      @close="closeDrawer"
      @success="onUpdateSuccess"
    />
    <AddMemberDialog
      v-else-if="drawerMode === 'addMember' && selectedOrg"
      :organization="selectedOrg"
      @close="closeDrawer"
      @success="onUpdateSuccess"
    />
    <RemoveMemberDialog
      v-else-if="drawerMode === 'removeMember' && selectedOrg"
      :organization="selectedOrg"
      @close="closeDrawer"
      @success="onUpdateSuccess"
    />
  </a-drawer>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
